package com.jsonpfy.webservices;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.jsonpfy.operations.List;

@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		JSONArray entities = null;

		String kind = request.getParameter("kind");

		String filterField = request.getParameter("filterField");

		String sortField = request.getParameter("sortField");

		String sortDirection = request.getParameter("sortDirection");

		if (filterField != null) {

			String filterValue = request.getParameter("filterValue");

			entities = List.jsonListFilter(kind, filterField, filterValue,
					sortField, sortDirection);

		} else {

			String filterKeyField = request.getParameter("filterKeyField");

			if (filterKeyField != null) {

				String filterKeyKind = request.getParameter("filterKeyKind");

				String filterKeyValue = request.getParameter("filterKeyValue");

				entities = List
						.jsonListFilterKey(kind, filterKeyField, filterKeyKind,
								filterKeyValue, sortField, sortDirection);
			} else {

				entities = List.jsonList(kind, sortField, sortDirection);
			}
		}

		String answer = Utilities.getCallback(request.getParameter("callback"),
				entities.toString());

		response.getWriter().println(answer);
	}
}
